package cn.tradewin.pmp.services.security.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.pmp.persist.client.ContractMapper;
import cn.tradewin.pmp.persist.model.Contract;
import cn.tradewin.pmp.services.security.ContractService;

public class ContractServiceImpl implements ContractService {

	private final SqlSessionFactory sqlSessionFactory;

	public ContractServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public int AddContract(Contract contract) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			ContractMapper mapper = session.getMapper(ContractMapper.class);
			int iCount = mapper.insertSelective(contract);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int updContract(Contract contract) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			ContractMapper mapper = session.getMapper(ContractMapper.class);
			int iCount = mapper.updateByPrimaryKey(contract);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int DelContracts(List<String> contracts) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			ContractMapper mapper = session.getMapper(ContractMapper.class);
			int iDels = mapper.deleteByPrimaryKeyList(contracts);
			if (iDels > 0) {
				session.commit();
			}
			return iDels;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public List<Contract> getAllContracts() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			ContractMapper mapper = session.getMapper(ContractMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public Contract findContractByPrimary(String contractNo) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			ContractMapper mapper = session.getMapper(ContractMapper.class);
			return mapper.selectByPrimaryKey(contractNo);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}
}
